<template>
	<view class="filter-model">
		<view class="model-content" @click="showFuc">
			<view class="model-content-title">
				筛选
				<image v-if="!disabled" :style="{ transform: showFilter ? ' rotate(180deg)' : ' rotate(0deg)' }" src="/static/images/down_pie.png" mode=""></image>
				<view class="line"></view>
			</view>
			<view class="model-content-all" v-if="showConditions">全部项目</view>
			<view class="model-content-tags" v-else>
				<view class="model-content-tags-item" v-for="(item, index) in chooseArr" :key="index" @click="removeItem(item, index)">
					{{ item.name }}
					<image src="/static/images/close_btn.png" mode="" v-if="!disabled"></image>
				</view>
			</view>
		</view>
		<filter-drawer
			:nodeAll="false"
			:chooseData="choosed"
			:filterList="filterList"
			:comfireText="comfireText"
			:show="showFilter"
			:keyMap="keyMap"
			ref="filter-drawer"
			@closed="handleClose"
			@submit="submitFilter"
			@chooseTag="getResultCount"
		></filter-drawer>
	</view>
</template>

<script>
import filterDrawer from '@/components/filter-drawer/filter-drawer.vue';
import { getBuildingType, getBrand } from '@/apis/barrierSearch.js';
import { getElevatorList } from '@/apis/barrierSearch.js';
import { removeEmpty } from '@/utils/utils.js';
export default {
	name: 'filter-model',
	components: { filterDrawer },
	props: {
		disabled: {
			type: Boolean,
			default: false
		},
		all: {
			type: Boolean,
			default: true
		},
		csd: {
			type: Object,
			default: () => {
				return {};
			}
		},
		userIds:{
			type:String,
			default:''
		}
	},
	data() {
		return {
			filterList: [
				{ title: '合同', key: 'contractStatus', list: [{ name: '到期未签', value: 1 }, { name: '即将到期', value: 3 }] },
				{ title: '年审类型', key: 'useTypes', list: [{ name: '年审', value: 0 }, { name: '非年审', value: 1 }] }
			],
			choosed: {},
			showFilter: false,
			allChecked: true,
			chooseArr: [],
			comfireText: '确定',
			keyMap: {}
		};
	},
	created() {
		this.getBuildingType();
		this.allChecked = this.all;
		this.choosed = this.csd;
		// this.setChooseArr();
		setTimeout(()=>{
		 this.setChooseArr();
		},500);
		// this.setChooseArr();
		// this.getBrand();
	},
	computed: {
		showConditions() { 
			let flag = false;
			flag = this.allChecked || Object.keys(this.choosed).length === 0 ? true : false;
			return flag;
		}
	},
	watch: {
	 
	},
	methods: {
		handleClose() {
			this.showFilter = false;
			let obj = {};
			this.chooseArr.forEach(item=>{
						   if (obj[item.key]) {
							   obj[item.key].push(item.value);
						   } else {
							    obj[item.key] = [];
							    obj[item.key].push(item.value);
						   }
			});
			this.choosed = obj;
			this.$refs['filter-drawer'].initData(obj);
		},
		showFuc() {
			if (this.disabled) {
				return;
			}
			this.showFilter = true;
			this.$refs['filter-drawer'].initData(this.choosed );
			this.handleCount({ allChecked: this.allChecked, choosed: this.choosed });
		},
		// 完成筛选
		filterd() { 
			this.$emit('filterd', {
				choosed: this.choosed,
				allChecked: this.allChecked
			});
		},
		// 保存筛选
		submitFilter(res) {
			// console.log(res, '点击保存');
			this.keyMap = res.keyMap;
			// console.log(this.keyMap, 222);
			this.allChecked = res.allChecked;
			this.choosed = res.choosed;
			this.showFilter = false;
			this.setChooseArr();
			this.filterd();
		},

		// 删除筛选item
		removeItem(item, index) {
			this.showFuc();
		},

		// 渲染已选标签
		setChooseArr() {
			let filterList = this.filterList;
			if (this.allChecked) {
				this.chooseArr = [];
				return;
			}
			let arr = []; 
			for (let key in this.choosed) {
				let obj = this.filterList.find((item, i) => {
					return item.key === key;
				}); 
				if (obj) {
					obj.list.forEach(e => {
						if (this.choosed[key].indexOf(e.value) != -1) {
							arr.push({
								...e,
								key
							});
						}
					});
				}
			}
			 
			this.chooseArr = arr; 
		},

		// 项目类型,品牌
		async getBuildingType() {
			const all = [getBrand(), getBuildingType()];	
		     await Promise.all(all).then(res => {
				if (res) {
					let arr1 = res[0].data.map(item => {
						return {
							name: item.brandName,
							value: item.id
						};
					});
					let arr2 = res[1].data.map(item => {
						return { name: item.dictValue, value: item.dictKey };
					});
					this.filterList.push(
						{
							title: '品牌',
							key: 'brandIds',
							list: arr1
						},
						{
							title: '项目类型',
							key: 'types',
							list: arr2
						}
					);
				}
			}); 
			this.setKeyMap(this.filterList);
		},
		setKeyMap(list) {
			const map = new Map();
			list.forEach(item => {
				map.set(item.key, { flag: false });
			});
			const obj = [...map.entries()].reduce((obj, [key, value]) => ((obj[key] = value), obj), {});
			// console.log(obj, 'flagMap');
			this.keyMap = obj;
		},
		handlegetElevatorList(obj) {
			return new Promise((resolve, reject) => {
				getElevatorList(obj)
					.then(res => {
						// console.log(res,7888)
						if (res) {
							resolve(res.data);
						}
					})
					.catch(() => {
						resolve({});
					});
			});
		},
		// 接受tag改变以及重置的
		getResultCount(res) {
			this.handleCount(res);
		},	
		// 获取点击筛选条件后的数量总数	
		async handleCount(res) {
			const { allChecked, choosed } = res; 
			if (!allChecked && !Object.keys(choosed).length) {
				this.comfireText = '确定';
				return;
			}
			let params = {
				size: 1000,
				current: 1,
				userIds:this.userIds
			};
			let query = {};
			if (Object.keys(choosed).length || allChecked) {
				if (Object.keys(choosed).length) {
					const map = new Map();

					for (let key in choosed) {
						map.set(key, choosed[key]);
					}
					const obj = [...map.entries()].reduce((obj, [key, value]) => ((obj[key] = value.join(',')), obj), {});

					query = obj;
				}
				const tempList = ['buildingId','buildingName','current','size'];
				let tempParams = Object.keys(choosed).length ? { ...query, ...params } : params;
				for (let key in tempParams ) {
                	if (!tempList.includes(key)) {
                		tempParams[key] = tempParams[key].split(',');
                	}
				}
				let count = await this.handlegetElevatorList(removeEmpty(tempParams));
				if (count.total > 0) {
					this.comfireText = `查看${count.total}条数据`;
				} else {
					uni.showToast({
						icon: 'none',
						title: '筛选结果为空 请重新选择条件'
					});
					this.comfireText = '完成';
				}
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.filter-model {
	width: 100%;
	.model-content {
		width: calc(100% - 40rpx);
		padding: 0 20rpx;
		display: flex;
		font-size: 26rpx;
		color: #333;
		padding-bottom: 20rpx;
		align-items: center;
		&-title {
			display: flex;
			font-weight: bold;
			letter-spacing: 1rpx;
			align-items: center;
			margin-right: 10rpx;
			image {
				width: 22rpx;
				height: 22rpx;
				transition: 0.3s all;
				margin: 4rpx 0rpx 0 7rpx;
			}
			.line {
				width: 2rpx;
				height: 30rpx;
				background-color: #ccc;
				margin-left: 12rpx;
			}
		}
		&-all {
			font-size: 24rpx;
			color: #999;
			margin-left: 12rpx;
		}
		&-tags {
			flex: 1;
			display: flex;
			flex-wrap: wrap;
			&-item {
				border: 2rpx solid #cccccc;
				padding: 0 4rpx 2rpx 8rpx;
				color: #666;
				border-radius: 4rpx;
				margin: 10rpx;
				font-size: 24rpx;
				image {
					width: 20rpx;
					height: 20rpx;
				}
			}
		}
	}
}
</style>
